package com.hs.javassist;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.CtNewMethod;

/**
 * @Author: hs
 * @Description:
 * @Date: Create in 16:07 2019/9/2
 */
public class MyAssist {


    public static Object getMyA() throws Exception {
        CtClass ctClass = ClassPool.getDefault().get("com.hs.javassist.MyA");
        String methodName = "add";
        CtMethod oldMethod = ctClass.getDeclaredMethod(methodName);
        String implName = methodName+"$Impl";
        oldMethod.setName(implName);
        CtMethod mnew = CtNewMethod.copy(oldMethod, methodName, ctClass, null);
        StringBuffer body = new StringBuffer();
        body.append("{System.out.println(\"之前植入代码\");\n");
        body.append("String result = "+implName+"($$);\n");
        body.append("System.out.println(\"之后植入代码\");\n");
        body.append("return result;\n}");
        mnew.setBody(body.toString());
        ctClass.addMethod(mnew);
        Object mya = ctClass.toClass().newInstance();
        return mya;
    }

    public static void main(String[] args) throws Exception {
        MyA myA = (MyA)getMyA();
        myA.add("shun");
    }


}
